﻿using DotNetCore.CAP;
using DotNetCore.CAP.Transport;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace CapHttp.Core;

public static class SqlSugarCapExtensions
{
    public static ICapTransaction BeginCapTransaction(this ISqlSugarClient client, ICapPublisher publisher,
        bool autoCommit = false)
    {
        var dispatcher = publisher.ServiceProvider.GetRequiredService<IDispatcher>();
        client.Ado.BeginTran();
        var transaction = new SqlSugarCapTransaction(dispatcher, client.Ado)
        {
            AutoCommit = autoCommit
        };
        return publisher.Transaction.Value = transaction;
    }
    
    public static ICapTransaction BeginCapTransaction(this ISqlSugarClient client, IDistributedEventPublisher publisher,
        bool autoCommit = false)
    {
        var dispatcher = publisher.CapPublisher.ServiceProvider.GetRequiredService<IDispatcher>();
        client.Ado.BeginTran();
        var transaction = new SqlSugarCapTransaction(dispatcher, client.Ado)
        {
            AutoCommit = autoCommit
        };
        return publisher.CapPublisher.Transaction.Value = transaction;
    }
}